<?php

namespace common\service;

use common\exception\LogicException;
use think\Exception;
use support\ErrorCode;
use common\model\TaskModel;
use support\SingletonTrait;
use common\model\EntityModel;

class DesignService
{
    use SingletonTrait;

    /**
     * 概念版本信息
     * @param int $taskId
     * @return array|mixed|void
     * @throws Exception
     */
    public function designVersions(int $taskId)
    {
        $task = model(TaskModel::class)->find($taskId);
        if (empty($task)) {
            throw new LogicException("task not found", ErrorCode::TASK_NOT_FOUND);
        }
        $designEntityId = $this->getDesignEntityId($task);
        if (empty($designEntityId)) {
            return [];
        }
        $latestStepTask = model(TaskModel::class)
            ->alias('t')
            ->join('step s on s.id = t.step_id')
            ->where(['t.entity_id' => $designEntityId, 's.is_dismantle_step' => 'no'])
            ->order('t.id desc')
            ->field('t.*')
            ->find();
        if (empty($latestStepTask)) {
            return [];
        }

        // 判断是否外包给当前租户了
        if (in_array($latestStepTask['executor_type'], ['outside', 'tenant_group'])) {
            $realOutSideTask = OrderService::getInstance()->getOutsideTaskByTaskId($latestStepTask['id']);
            if (empty($realOutSideTask)) {
                return [];
            }
            $latestStepTask = $realOutSideTask;
        }

        $versionFilter = [
            'version.module_id' => module_by_code('task')['id'],
            'version.link_id' => $latestStepTask['id'], 'version.is_publish' => 'yes',
        ];
        return VersionService::getInstance()->getActivityData($versionFilter, [1, 100]);
    }

    /**
     * 查询任务的概念id
     * @param array $task
     * @return false|int|mixed|string|null
     * @throws Exception
     */
    private function getDesignEntityId(array $task)
    {
        $taskEntityModule = module_by_id($task['entity_module_id']);
        switch ($taskEntityModule['code']) {
            case 'level':
            case 'asset':
                $designField = $taskEntityModule['code'] . '_design';
                $designId = model(EntityModel::class)
                    ->alias($taskEntityModule['code'])
                    ->where(['id' => $task['entity_id']])
                    ->field(transform_custom_fields([$designField], $taskEntityModule['code']))
                    ->value($designField);
                break;
            case 'design':
                $designId = $task['entity_id'];
                break;
            default:
                $designId = 0;
        }
        return $designId;
    }
}
